import math
import os
import sys
import time
import json

# 将工程目录加入包扫描
currPath = os.path.abspath(os.path.dirname(__file__))
srcPath = os.path.split(currPath)[0]
rootPath = os.path.split(srcPath)[0]
projectPath = os.path.split(rootPath)[0]
sys.path.append(projectPath)

from src.base import Consts
from tqdm import tqdm
from elasticsearch import Elasticsearch
from src.db.CcxDataCenterDb import CcxDataCenter
from src.db.ProdDb import ProdDb
from src.utils.LogUtils import Logger

logger = Logger()

es = Elasticsearch(
    [{'host': Consts.elasticsearch_url, 'port': Consts.elasticsearch_port}], timeout=3600
)


class syncQeV2Result:
    def __init__(self, logger, localDb, dataCenterDb):
        self.logger = logger
        self.localDb = localDb
        self.dataCenterDb = dataCenterDb

    # def __queryMaxTime__(self):
    #     sql = """
    #             SELECT max(last_edit_time)  from qe_result_manage
    #             order by id
    #         """
    #     return self.localDb.Query(sql, None)

    def writeEs(self, data):
        es.indices.create(index=Consts.enterprise_qe_rating, ignore=400)
        for item in tqdm(data, desc="es数据库保存/更新中...", position=0):
            item = dict(item)
            item.__setitem__('status', int.from_bytes(item.get('status'), byteorder='big', signed=True))
            item.__setitem__('effective', int.from_bytes(item.get('effective'), byteorder='big', signed=True))
            item.__setitem__('rating_date', str(item.get('rating_date')))
            body = {
                "query": {
                    "match": {
                        "id": item.get('id')
                    }
                },
                "track_total_hits": True
            }
            queryResult = es.search(index=Consts.enterprise_qe_rating, body=body)
            if len(queryResult['hits']['hits']) > 0:
                for updateItem in queryResult['hits']['hits']:
                    es.index(index=Consts.enterprise_qe_rating, doc_type='test-type', id=updateItem['_id'],
                             body=item)
            else:
                es.index(index=Consts.enterprise_qe_rating, doc_type='test-type', body=item)

    def __queryCityInvestQe__(self, maxTime: None):
        sql = """SELECT
                    id,
                    code,
                    name,
                    credit_code,
                    fc_code,
                    qe_level,
                    `year`,
                    status,
                    evaluator,
                    rating_date,
                    change_reason,
                    last_edit_time,
                    last_edit_user,
                    effective
                FROM
                    `data-center`.qe_result_manage
                order by id
                 AND 
                last_edit_time > %s"""
        if maxTime == None or maxTime[0]["last_edit_time"] == None:
            last_edit_time = 0
        else:
            last_edit_time = maxTime[0]["last_edit_time"]
        self.logger.info("数据最大时间=======%s" % last_edit_time)
        return self.dataCenterDb.Query(sql, last_edit_time)


if __name__ == "__main__":
    logger = Logger()
    localDb = ProdDb(logSql=False, autocommit=True)
    dataCenterDb = CcxDataCenter(logSql=False, autocommit=True)
    t = time.perf_counter()
    logger.info("========同步2.0qe评级管理数据 开始 ========")
    syncData = syncQeV2Result(logger=logger, localDb=localDb, dataCenterDb=dataCenterDb)
    # 最大时间
    # maxId = syncData.__queryMaxTime__()
    data = syncData.__queryCityInvestQe__(None)
    syncData.writeEs(data)
    cast = (time.perf_counter() - t)
    m = math.floor(cast / 60)
    s = cast - m * 60
    logger.info('总耗时: %d分%.3f秒' % (m, s))
    logger.info("========同步2.0qe评级管理数据 结束 ========")
